package com.yaowk.sfp.file.oss;

import com.aliyun.oss.OSSClient;
import com.yaowk.sfp.common.base.utils.StringUtils;
import com.yaowk.sfp.file.api.BaseFileUtils;
import com.yaowk.sfp.file.api.exception.FileException;
import com.yaowk.sfp.file.api.model.FileModel;
import com.yaowk.sfp.file.server.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 小凯
 **/
@Slf4j
@Service
public class OssFileUtils extends BaseFileUtils {

    @Value("${yaowk.file.oss.endpoint}")
    private String endpoint;
    @Value("${yaowk.file.oss.bucket}")
    private String bucket;
    @Value("${yaowk.file.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${yaowk.file.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${yaowk.file.oss.quality:Q_100}")
    private String quality;


    @Autowired
    private IFileService fileService;

    private static final DateFormat FORMAT = new SimpleDateFormat("yyyy/MM/dd/");

    @Override
    public FileModel upload(MultipartFile file) {
        FileModel fileModel = buildFileModel(file);

        FileModel param = new FileModel();
        param.setMd5(fileModel.getMd5());
        param.setSize(fileModel.getSize());

        List<FileModel> all = fileService.findAll(param);
        if (CollectionUtils.isNotEmpty(all)) {
            fileModel = all.get(0);
        } else {
            String dir = FORMAT.format(new Date());
            String extension = getExtension(fileModel.getName());
            String fileName = fileModel.getMd5() + fileModel.getSize() + extension;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("https://")
                    .append(bucket)
                    .append(".")
                    .append(endpoint)
                    .append("/")
                    .append(dir)
                    .append(fileName);
            if (StringUtils.isNoneBlank(quality) && !".gif".equalsIgnoreCase(extension)) {
                stringBuilder.append("?x-oss-process=image/format,jpg/quality,");
                stringBuilder.append(quality);
            }
            fileModel.setFile(stringBuilder.toString());
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            try {
                ossClient.putObject(bucket, dir + fileName, file.getInputStream());
            } catch (IOException e) {
                log.info("OSS文件上传错误", e);
                throw new FileException("文件上传错误");
            } finally {
                ossClient.shutdown();
            }
            fileModel = fileService.save(fileModel);
        }
        return fileModel;
    }
}
